<template>
    <div class="app-container">
        <el-card>
            <el-page-header @back="goBack">
                <template #content>
                    <div class="flex items-center" style="display:flex; justify-content:space-between;">
                        <div style="display: flex; align-items: center;">
                            <div>
                                {{ route.query.readonly ? '查看保养计划' : route.query.id ? '编辑保养计划' : '新增保养计划' }}
                            </div>
                            <el-tag v-if="route.query.code" :type="tagType" style="margin-left: 10px;">{{ route.query.code
                            }}</el-tag>
                        </div>
                    </div>
                </template>
                <template #extra>
                    <div>
                        <el-button v-if="!readonly" class="button" type="primary" @click="handleSubmit"> 保 存
                        </el-button>
                    </div>
                </template>
            </el-page-header>
        </el-card>
        <el-card style="margin-top: 10px;">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled  title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">基本信息</span>
                    </template>
                    <div>
                        <el-form :model="form" :rules="rules" :disabled="readonly" ref="maintenanceRef" label-width="130px">
                            <el-row :gutter="20">
                                <!-- <el-col :span="8">
                                    <el-form-item label="保养计划编码" prop="code">
                                        <el-input v-model="form.code" placeholder="请输入保养计划编码" maxlength="30"
                                            style="width: 100%;" />
                                    </el-form-item>
                                </el-col> -->
                                <el-col :span="8">
                                    <el-form-item label="保养计划名称" prop="name">
                                        <el-input v-model="form.name" placeholder="请输入计划名称" style="width: 100%;" />

                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="保养计划类型" prop="ctype">
                                        <el-select v-model="form.ctype" class="m-2" placeholder="选择计划类型"
                                            style="width: 100%;" @change="weekMonth">
                                            <el-option v-for="item in mes_care_plantype" :key="item.value"
                                                :label="item.label" :value="item.value" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="状态">
                                        <el-select v-model="form.status" class="m-2" placeholder="选择状态"
                                            style="width: 100%;">
                                            <el-option v-for="item in mes_people_status" :key="item.value"
                                                :label="item.label" :value="item.value" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>

                            </el-row>
                            <el-row :gutter="20">
                                <!-- <el-col :span="8" v-if="!Day">
                                    <el-form-item label="计划开始时间" prop="startTime">
                                        <el-date-picker v-model="form.startTime" style="width: 100%;" type="date"
                                            placeholder="选择计划开始时间" format="YYYY-MM-DD" @change="comparisonTime"
                                            value-format="YYYY-MM-DD" />
                                    </el-form-item>
                                </el-col> -->
                                <el-col :span="8">
                                    <el-form-item label="计划开始时间" prop="startTime">
                                        <el-date-picker v-model="form.startTime" style="width: 100%;"
                                            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                            @change="comparisonTime" type="datetime" placeholder="选择计划开始时间" />
                                    </el-form-item>
                                </el-col>
                                <!-- <el-col :span="8" v-if="!Day">
                                    <el-form-item label="计划结束时间" prop="endTime">
                                        <el-date-picker v-model="form.endTime" style="width: 100%;" type="date"
                                            placeholder="选择计划结束时间" format="YYYY-MM-DD" @change="comparisonTime"
                                            value-format="YYYY-MM-DD" />
                                    </el-form-item>
                                </el-col> -->
                                <el-col :span="8">
                                    <el-form-item label="计划结束时间" prop="endTime">
                                        <el-date-picker v-model="form.endTime" style="width: 100%;"
                                            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                            @change="comparisonTime" type="datetime" placeholder="选择计划结束时间" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8" v-if="Week">
                                    <el-form-item label="生成日期" prop="planMultiple">
                                        <el-select v-model="form.planMultiple" placeholder="请选择" clearable multiple
                                            style="width: 300px">
                                            <el-option v-for="(item, index) in weekOptions" :key="index" :label="item.label"
                                                :value="item.value"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8" v-if="Month">
                                    <el-form-item label="生成日期" prop="planMultiple">
                                        <el-select v-model="form.planMultiple" placeholder="请选择" clearable
                                            style="width: 300px" multiple>
                                            <el-option v-for="(day, index) in MonthOptions" :key="index" :label="day"
                                                :value="day"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>


                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="下发部门" prop="deptCode">
                                        <el-tree-select style="width:300px" v-model="form.deptCode" :data="deptOptions"
                                            :props="{ value: 'id', label: 'label', children: 'children' }"
                                            @node-click="handleChange" value-key="id" check-strictly />
                                    </el-form-item>
                                </el-col>

                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="执行周期规则">
                                        <el-input v-model="form.cycleRule" type="textarea" placeholder="请输入内容"
                                            style="width: 100%;"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="执行周期描述">
                                        <el-input v-model="form.cycleRuleDes" type="textarea" placeholder="请输入内容"
                                            style="width: 100%;"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="24">
                                    <el-form-item label="备注">
                                        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"
                                            style="width: 100%;"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-card>
        <el-card style="margin-top: 10px;">
            <el-collapse v-model="activeNames">
                <el-collapse-item disabled  title="基本信息" name="1">
                    <template #title>
                        <el-icon style="color: #4479F6;">
                            <Position />
                        </el-icon> <span class="title">关联设备</span>
                    </template>
                    <div>
                        <el-button style="margin-bottom: 5px;" :disabled="readonly" type="primary" size="small" plain
                            icon="Plus" @click="handleChoice">关联 设备/机台</el-button>
                        <el-table :data="mesMachineCarereationList" border style="width: 100%">
                            <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="machineNo" label="设备编码" align="center" />
                            <el-table-column prop="machineName" label="设备名称" align="center" />
                            <el-table-column fixed="right" v-if="!readonly" label="操作" align="center">
                                <template #default="scope">
                                    <el-button link type="primary" size="small" @click="handleDel(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-collapse-item>
            </el-collapse>
        </el-card>

        <machineDialog :visible="visibleMachine" @changeUpdate="changeUserData" @cancel="() => { visibleMachine = false }">
        </machineDialog>
    </div>
</template>

<script setup>
import { computed } from 'vue';
import machineDialog from '@/components/SearchWorkBenchS'
import useTagsViewStore from '@/store/modules/tagsView'
const tagsViewStore = useTagsViewStore()
import { getCare, addCare, updateCare } from '@/api/maintenance/plan.js'

import { deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { mes_care_plantype, mes_people_status } = proxy.useDict('mes_care_plantype', 'mes_people_status');
import { ElMessage, ElMessageBox } from 'element-plus'
const router = useRouter();
const route = useRoute();
const activeNames = ['1']
const maintenanceRef = ref(null)


const mesMachineCarereationList = ref([])
const readonly = ref(false)
const Week = ref(false)
const Month = ref(false)
const Day = ref(false)
const deptOptions = ref(undefined);
const visibleMachine = ref(false)
const data = reactive({
    weekOptions: [
        {
            value: '1',
            label: '周一',
        },
        {
            value: '2',
            label: '周二',
        },
        {
            value: '3',
            label: '周三',
        },
        {
            value: '4',
            label: '周四',
        },
        {
            value: '5',
            label: '周五',
        },
        {
            value: '6',
            label: '周六',
        },
        {
            value: '7',
            label: '周日',
        },
    ],
    MonthOptions: [
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        '10',
        '11',
        '12',
        '13',
        '14',
        '15',
        '16',
        '17',
        '18',
        '19',
        '20',
        '21',
        '22',
        '23',
        '24',
        '25',
        '26',
        '27',
        '28',
        '29',
        '30',
        '31',
    ],
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        name: null,
    },
    form: {},
    rules: {
        name: [{ required: true, message: "保养计划名称不能为空", trigger: "blur" }],
        ctype: [{ required: true, message: "保养计划类型不能为空", trigger: "blur" },],
        code: [{ required: true, message: "保养计划编码不能为空", trigger: ["blur", "change"] }],
        startTime: [{ required: true, message: "开始时间不能为空", trigger: "blur" },],
        endTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" },],
        planMultiple: [{ required: true, message: "生成日期不能为空", trigger: "blur" }],
        deptCode: [{ required: true, message: "下发部门不能为空", trigger: "blur" }],
    },
});
const { form, rules, queryParams, weekOptions, MonthOptions } = toRefs(data);
const tagType = computed(() => {
    return route.query.status == 0 ? '' : 'danger';
});
readonly.value = route.query.readonly
if (route.query.id) {
    getCare(route.query.id).then(response => {
        form.value = response.data
        form.value.status = form.value.status + ''
        form.value.ctype = form.value.ctype + ''
        form.value.deptCode = Number(form.value.deptCode)
        mesMachineCarereationList.value = response.data.mesMachineCarereationList
    })
} else {
    form.value = {}
}
/** 查询部门下拉树结构 */
function getDeptTree() {
    deptTreeSelect().then(response => {
        deptOptions.value = response.data;
    });
};
const handleChange = (data) => {
    console.log('data', data)
    form.value.deptName = data.label;
}
const comparisonTime = (data) => {
    const providedDate = new Date(data); // 将提供的日期字符串转换为 Date 对象
    const currentDate = new Date(); // 获取当前日期
    // 提取日期部分，不考虑时间
    const providedDateWithoutTime = new Date(providedDate.getFullYear(), providedDate.getMonth(), providedDate.getDate());
    const currentDateWithoutTime = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate());
    if (providedDateWithoutTime < currentDateWithoutTime) {
        form.value.startTime = undefined
        form.value.endTime = undefined
        return ElMessage({
            message: '日期不能小于当前日',
            type: 'warning',
        });

    }
}
const weekMonth = (item) => {
    form.value.planMultiple = []
    console.log('item', item)
    Day.value = item == 4
    Week.value = item == 1;
    Month.value = item == 2;

}
const handleChoice = () => {
    visibleMachine.value = true

}
const changeUserData = (row) => {
    const codeSet = new Set(mesMachineCarereationList.value.map(data => data.machineNo));
    row.forEach(item => {
        if (!codeSet.has(item.machineNo)) {
            mesMachineCarereationList.value.push({ machineNo: item.machineNo, machineName: item.machineName, });
            codeSet.add(item.machineNo);
        }
    });
    visibleMachine.value = false
}


const handleDel = (row) => {
    console.log('row', row)
    const index = mesMachineCarereationList.value.indexOf(row);
    if (index !== -1) {
        mesMachineCarereationList.value.splice(index, 1);
    }
}

//保存

const handleSubmit = () => {
    if (!mesMachineCarereationList.value.length && mesMachineCarereationList.value.length === 0) {
        return ElMessage({
            message: '请至少选择一个设备',
            type: 'warning',
        });
    }
    maintenanceRef.value.validate((valid) => {
        if (valid) {
            ElMessageBox.confirm(`是否立即生成保养记录`, '提示', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning',
            }).then(() => {
                // 用户点击了确定按钮
                form.value.hasDetail = 1;
            }).catch(() => {
                form.value.hasDetail = 0;
            }).finally(() => {
                // 在 finally 中设置 hasDetail 后再执行提交逻辑
                const formData = { ...form.value };
                formData.mesMachineCarereationList = mesMachineCarereationList.value;
                formData.planMultiple = formData.planMultiple.join(',');
                console.log('formData', formData);
                if (formData.id) {
                    updateCare(formData).then(response => {
                        if (response.code === 200) {
                            ElMessage({
                                message: '编辑成功',
                                type: 'success',
                            });
                            goBack();
                        }
                    }).catch(() => {
                        formData.planMultiple = formData.planMultiple.split(',');

                    });
                } else {
                    formData.status = 0;
                    addCare(formData).then(response => {
                        if (response.code === 200) {
                            ElMessage({
                                message: '新增成功',
                                type: 'success',
                            });
                            goBack();
                        }
                    }).catch(() => {
                        formData.planMultiple = formData.planMultiple.split(',');

                    });;
                }
            });
        }
    });
};

//  返回
const goBack = () => {
    tagsViewStore.delView(route)
    router.back()
}
getDeptTree();
</script>

<style lang="scss" scoped></style>